package tech.aistar.prj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import tech.aistar.prj.entity.Pet;
import tech.aistar.prj.mapper.PetMapper;
import tech.aistar.prj.service.IPetService;
import tech.aistar.prj.util.MybatisUtil;

import java.util.List;

/**
 * 本类功能:
 *
 * @author cxylk
 * @date 2020/9/16 20:05
 */
public class PetServiceImpl implements IPetService {
    @Override
    public List<Pet> findAll() {
        SqlSession sqlSession= MybatisUtil.getSqlSession();
        PetMapper petMapper=sqlSession.getMapper(PetMapper.class);
        List<Pet> pets=petMapper.findAll();

        sqlSession.close();
        return pets;
    }

    @Override
    public List<Pet> search(String typeId, String name) {
        SqlSession sqlSession= MybatisUtil.getSqlSession();
        PetMapper petMapper=sqlSession.getMapper(PetMapper.class);

        //为空就让它等于-1，因为-1就是默认的值
        typeId=typeId==null?"-1":typeId;
        //String转换成long
        Long tid=Long.valueOf(typeId);

        List<Pet> pets=petMapper.search(tid,name);

        sqlSession.close();
        return pets;
    }

    @Override
    public int delById(Integer id) {
        SqlSession sqlSession= MybatisUtil.getSqlSession();
        PetMapper petMapper=sqlSession.getMapper(PetMapper.class);

        int count=petMapper.delById(id);

        sqlSession.commit();
        sqlSession.close();

        return count;
    }

    @Override
    public PageInfo<Pet> findByPage(String typeId, String name, Integer pageNow, Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);

        List<Pet> pets=search(typeId,name);

        PageInfo<Pet> petPageInfo=new PageInfo<>(pets);

        return petPageInfo;
    }

    @Override
    public void save(Pet pet) {
        SqlSession sqlSession= MybatisUtil.getSqlSession();
        PetMapper petMapper=sqlSession.getMapper(PetMapper.class);
        petMapper.save(pet);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public Pet findById(Integer id) {
        SqlSession sqlSession= MybatisUtil.getSqlSession();
        PetMapper petMapper=sqlSession.getMapper(PetMapper.class);
        Pet pet=petMapper.findById(id);
        return pet;
    }

    @Override
    public int update(Pet pet) {
        SqlSession sqlSession=MybatisUtil.getSqlSession();
        PetMapper petMapper=sqlSession.getMapper(PetMapper.class);
        int count=petMapper.update(pet);
        sqlSession.commit();
        sqlSession.close();
        return count;
    }
}
